﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Windows.Input;
using Microsoft.Practices.Prism.Commands;
using System.Windows;
using CorpAbreu.Login.ServiceReference1;
using System.Windows.Controls;
using Microsoft.Practices.Prism.Events;
using CorpAbreu.Common;

namespace CorpAbreu.Login.ViewModels
{
    public class LoginViewModel : CorpAbreu.Common.BaseClasses.ViewModelBase
    {
        private readonly IEventAggregator _eventAggregator;

        public LoginViewModel(IEventAggregator EventAggregator)
        {
            
            this._eventAggregator = EventAggregator;
            

            Abreu.Framework.WebServices.ContractManager.AuthenticationFailed += new EventHandler<Abreu.Framework.WebServices.AuthenticationEventArgs>(ContractManager_AuthenticationFailed);
            Abreu.Framework.WebServices.ContractManager.AuthenticationSuccessful += new EventHandler<Abreu.Framework.WebServices.AuthenticationEventArgs>(ContractManager_AuthenticationSuccessful);

            Abreu.Framework.WebServices.ContractManager.ClearTokens();
            Abreu.Framework.WebServices.ContractManager.WindowsAuthEnabled = true;
            Abreu.Framework.WebServices.ContractManager.ForceAuthentication();
        }

        void ContractManager_AuthenticationSuccessful(object sender, Abreu.Framework.WebServices.AuthenticationEventArgs e)
        {
            this._eventAggregator.GetEvent<TesteSelectedEvent>().Publish("Bem-vindo" + UserName);
            DialogResult = true;
        }

        void ContractManager_UserNamePasswordAuthentication(object sender, Abreu.Framework.WebServices.AuthenticationEventArgs<System.ServiceModel.Security.UserNamePasswordClientCredential> e)
        {
            //Abreu.Framework.WebServices.ContractManager.WindowsAuthEnabled = false;
            //throw new NotImplementedException();
            e.ClientCredential.Password = Password;
            e.ClientCredential.UserName = UserName;
        }

        void ContractManager_AuthenticationFailed(object sender, Abreu.Framework.WebServices.AuthenticationEventArgs e)
        {
            //throw new NotImplementedException();
            if(!Abreu.Framework.WebServices.ContractManager.WindowsAuthEnabled)
                Mensagem = "Login inválido";
        }


        public ICommand Valida
        {
            get { return new DelegateCommand(IsValid); }
        }

        private bool? _DialogResult;
        public bool? DialogResult
        {
            get { return _DialogResult; }
            set
            {
                if (value != _DialogResult)
                {
                    _DialogResult = value;
                    OnPropertyChanged("DialogResult");
                }
            }
        }

        private string _UserName;
        public string UserName
        {
            get { return _UserName; }
            set
            {
                if (value != _UserName)
                {
                    _UserName = value;
                    OnPropertyChanged("UserName");
                }
            }
        }

        private string _Password;
        public string Password
        {
            get { return _Password; }
            set
            {
                if (value != _Password)
                {
                    _Password = value;
                    OnPropertyChanged("Password");
                }
            }
        }

        private string _Mensagem;
        public string Mensagem
        {
            get { return _Mensagem; }
            set
            {
                if (value != _Mensagem)
                {
                    _Mensagem = value;
                    OnPropertyChanged("Mensagem");
                }
            }
        }
        


        void IsValid()
        {
            //Valida Acesso no WS

            Password = PasswordHelper.PasswordText;

            Abreu.Framework.WebServices.ContractManager.UserNamePasswordAuthentication += new EventHandler<Abreu.Framework.WebServices.AuthenticationEventArgs<System.ServiceModel.Security.UserNamePasswordClientCredential>>(ContractManager_UserNamePasswordAuthentication);
            Abreu.Framework.WebServices.ContractManager.ClearTokens();
            Abreu.Framework.WebServices.ContractManager.WindowsAuthEnabled = false;
            Abreu.Framework.WebServices.ContractManager.ForceAuthentication();
        }
    }

    public static class DialogCloser
    {
        public static readonly DependencyProperty DialogResultProperty =
            DependencyProperty.RegisterAttached(
                "DialogResult",
                typeof(bool?),
                typeof(DialogCloser),
                new PropertyMetadata(DialogResultChanged));

        private static void DialogResultChanged(
            DependencyObject d,
            DependencyPropertyChangedEventArgs e)
        {
            var window = d as Window;
            if (window != null)
                window.DialogResult = e.NewValue as bool?;
        }
        public static void SetDialogResult(Window target, bool? value)
        {
            target.SetValue(DialogResultProperty, value);
        }
    }

    public static class PasswordHelper
    {
        public static readonly DependencyProperty PasswordProperty =
            DependencyProperty.RegisterAttached("Password",
            typeof(string), typeof(PasswordHelper),
            new FrameworkPropertyMetadata(string.Empty, OnPasswordPropertyChanged));

        public static readonly DependencyProperty AttachProperty =
            DependencyProperty.RegisterAttached("Attach",
            typeof(bool), typeof(PasswordHelper), new PropertyMetadata(false, Attach));

        private static readonly DependencyProperty IsUpdatingProperty =
           DependencyProperty.RegisterAttached("IsUpdating", typeof(bool),
           typeof(PasswordHelper));

        public static string PasswordText { get; set; }

        public static void SetAttach(DependencyObject dp, bool value)
        {
            dp.SetValue(AttachProperty, value);
        }

        public static bool GetAttach(DependencyObject dp)
        {
            return (bool)dp.GetValue(AttachProperty);
        }

        public static string GetPassword(DependencyObject dp)
        {
            return (string)dp.GetValue(PasswordProperty);
        }

        public static void SetPassword(DependencyObject dp, string value)
        {
            dp.SetValue(PasswordProperty, value);
        }

        private static bool GetIsUpdating(DependencyObject dp)
        {
            return (bool)dp.GetValue(IsUpdatingProperty);
        }

        private static void SetIsUpdating(DependencyObject dp, bool value)
        {
            dp.SetValue(IsUpdatingProperty, value);
        }

        private static void OnPasswordPropertyChanged(DependencyObject sender,
            DependencyPropertyChangedEventArgs e)
        {
            PasswordBox passwordBox = sender as PasswordBox;
            passwordBox.PasswordChanged -= PasswordChanged;

            if (!(bool)GetIsUpdating(passwordBox))
            {
                passwordBox.Password = (string)e.NewValue;
            }
            passwordBox.PasswordChanged += PasswordChanged;
        }

        private static void Attach(DependencyObject sender,
            DependencyPropertyChangedEventArgs e)
        {
            PasswordBox passwordBox = sender as PasswordBox;

            if (passwordBox == null)
                return;

            if ((bool)e.OldValue)
            {
                passwordBox.PasswordChanged -= PasswordChanged;
            }

            if ((bool)e.NewValue)
            {
                passwordBox.PasswordChanged += PasswordChanged;
            }
        }

        private static void PasswordChanged(object sender, RoutedEventArgs e)
        {
            PasswordBox passwordBox = sender as PasswordBox;
            SetIsUpdating(passwordBox, true);
            SetPassword(passwordBox, passwordBox.Password);
            SetIsUpdating(passwordBox, false);
            PasswordText = passwordBox.Password;
        }
    }


}
